#include "STC_NEW_8051.H"

unsigned char pca0_Count,pca1_Count;
bit pwmRunning;
sbit CW0 = P1^1;
sbit CW1 = P1^2;

void timer0(void) interrupt 1{
    TH0 = 0xFF;
    TL0 = 0xF6;
    TR0 = 1; 
}

void PCA(void) interrupt 7{
	if(pca0_Count==0){
		CCAP0L = 0x00;
    	CCAP0H = 0x00;
	}
	else{
		pca0_Count--;
	}
	if(pca1_Count==0){
		CCAP1L = 0x00;
    	CCAP1H = 0x00;
	}
	else{
		pca1_Count--;		
	}
	if(pca0_Count==0 && pca1_Count==0)pwmRunning = 0;
	CCF0 = 0;
	CCF1 = 0;
}	

void SetPWM(bit dt0, unsigned char ch0_step,bit dt1, unsigned char ch1_step){
	while(pwmRunning==1);
	CW0 = dt0;
	CW1 = dt1;
	pca0_Count = ch0_step;
	pca1_Count = ch1_step;
	CCAP0L = 0x7F;
    CCAP0H = 0x7F;
	CCAP1L = 0x7F;
    CCAP1H = 0x7F;
	
	pwmRunning = 1;
}

void InitPWM(void){
    //Setup T0 (default in 12T Mode)
    TMOD = 0x01;//0000 0001  T0 work in Method 1, 16bit counter.
    TH0 = 0xFF;TL0 = 0xF6; //0xFFF6,cycle:5us, fosc=22.1184Mhz, PWM frequency:781Hz.
    EA = 1;
    ET0 = 1;TR0 = 1;//open T0 intrreupt,start T0.
    EX0 = 1;IT0 = 1;//open INT0 interrupt.
    //Setup PCA
    CMOD = 0x04;   //0000 0100  CPS:010, T0 as the input source
    CL = 0x00;     //PCA counter
    CH = 0x00;
    CCAP0L = 0x7F; //same as CCAP0H
    CCAP0H = 0x7F; //duty load 50%
    CCAPM0 = 0x53; //0101 0011 PCA 8 bit pwm,with trailing edge interrupt
	CCAP1L = 0x7F; //same as CCAP0H
    CCAP1H = 0x7F; //duty load 50%
    CCAPM1 = 0x53; //0101 0011 PCA 8 bit pwm, with trailing edge interrupt
    CR = 1;//Start PCA
	SetPWM(0,0,0,0);
}